import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '../views/layout.vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: layout,
    redirect: '/article',
    children: [
      { path: 'article', component: () => import('../views/article.vue') },
      { path: 'collect', component: () => import('../views/collect.vue') },
      { path: 'like', component: () => import('../views/like.vue') },
      { path: 'user', component: () => import('../views/user.vue') }
    ]
  },
  { path: '/detail/:id', component: () => import('../views/detail.vue') },
  { path: '/login', component: () => import('../views/login.vue') },
  { path: '/register', component: () => import('../views/register.vue') }
]
// 添加白名单数组
const whiteList = ['/register', '/login']
const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      Toast.fail('您没有登录  请登录！')
    }
  }
})
export default router
